#!/usr/bin/env python3
"""This is just a simple authentication example.

Please see the `OAuth2 example at FastAPI <https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/>`_  or
use the great `Authlib package <https://docs.authlib.org/en/v0.13/client/starlette.html#using-fastapi>`_ to implement a classing real authentication system.
Here we just demonstrate the NiceGUI integration.
"""
from typing import Optional

from fastapi import Request
from fastapi.responses import RedirectResponse
from starlette.middleware.base import BaseHTTPMiddleware

from nicegui import app, ui
from utils import unrestricted_page_routes


class AuthMiddleware(BaseHTTPMiddleware):
    """This middleware restricts access to all NiceGUI pages.
    认证中间件，限制所有 NiceGUI 页面访问。如未认证，重定向到登录页面。
    It redirects the user to the login page if they are not authenticated.
    """

    async def dispatch(self, request: Request, call_next):
        """
        根据用户是否已认证，决定是否需要重定向到登录页面。

        Args:
            request (Request): 请求对象。
            call_next: 调用下一个中间件或处理程序的函数。

        Returns:
            Union[Response, None]: 如果用户未认证且请求路径不在白名单中，返回重定向到登录页面的Response对象；
                                    否则返回调用call_next后返回的结果。
        """
        if not app.storage.user.get("authenticated", False):
            if (
                not request.url.path.startswith("/_nicegui")
                and request.url.path not in unrestricted_page_routes
            ):
                app.storage.user["referrer_path"] = (
                    request.url.path
                )  # remember where the user wanted to go
                return RedirectResponse("/login")
        return await call_next(request)
